package com.cf.limit.core;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;
import com.cf.limit.core.frequency.IpLimitChecker;
import com.cf.spel.SpELService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * cf-game-ZLimitAspect
 * 接口频率访问限制切面
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/4/23 上午 10:45
 */
@Slf4j
@Aspect
@Order(-100)
public class ZLimitAspect {

    @Autowired
    private SpELService spELService;

    @Autowired
    private IpLimitChecker ipLimitChecker;

    private Map<String, RequestChecker> requestCheckerMap = new HashMap();

    /**
     * 方法执行时
     */
    @Pointcut("@annotation(RequestLimit)")
    public void ZLogAspect() {
    }

    @Around("@annotation(RequestLimit)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        boolean check = check(pjp);

        if (check) {
            return pjp.proceed();
        } else {
            log.info("校验不通过，不予放行");
            throw new BizException(EnumReturnCode.ERROR.getCode(), "访问过于频繁！");
        }
    }

    private boolean check(ProceedingJoinPoint pjp) throws Throwable {
        //拦截的方法
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();

        RequestLimit requestLimit = method.getAnnotation(RequestLimit.class);

        //拦截的放参数类型
        Object[] parameterArgs = pjp.getArgs();

        String spELValue = spELService.getSpELValue(method, requestLimit.key(), String.class, parameterArgs);
        if (StringUtils.isEmpty(spELValue)) {
            spELValue = pjp.getTarget().getClass().getSimpleName() + "-" + method.getName();
            log.info("limit el表达式【{}】未找到值，将限制key设置为【{}】！！！", requestLimit.key(), spELValue);
        }
        //检测
        return ipLimitChecker.check(spELValue, requestLimit);
    }

}
